import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/AudioPlayBar.dart';
import 'package:hitutor/Widget/AudioPlayerBarLocal.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyInput.dart';
import 'package:hitutor/Widget/MyPage.dart';
import 'package:record/record.dart';

class SubmitHomeWork extends StatefulWidget {
  String teacher;
  String teacherId;
  String date;
  int questionId;
  String question;
  Function() onSendDone;

  SubmitHomeWork(this.teacher, this.teacherId, this.date, this.questionId, this.question, {required this.onSendDone});

  @override
  State<StatefulWidget> createState() {
    return _SubmitHomeWork();
  }
}

class _SubmitHomeWork extends State<SubmitHomeWork> {
  TextEditingController answerController = TextEditingController();
  List<File> files = [];
  String audioPath = "";

  chooseFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
        // type:FileType.media
        );
    //todo 驗證後綴名
    if (result != null && result.files.single.path != null) {
      var file = File(result.files.single.path!);
      files.add(file);
      setState(() {});
    }
  }

  delFile(int i) {
    files.removeAt(i);
    setState(() {});
  }

  sendClick() async {
    String answer = answerController.text;
    Map<String, dynamic> params = {"homeworkQuestionId": widget.questionId, "answer": answer};

    if (files.length > 0) {
      List<MultipartFile> uploadFiles = [];
      for (var item in files) {
        MultipartFile file = await MultipartFile.fromFile(item.path);
        uploadFiles.add(file);
      }
      params["files"] = uploadFiles;
    }

    if (audioPath.isNotEmpty) {
      var realPath = audioPath;
      if (Theme.of(context).platform == TargetPlatform.iOS) {
        realPath = audioPath.replaceFirst("file://", "");
      }
      print("realPath:$realPath");
      MultipartFile recordFile = await MultipartFile.fromFile(realPath);
      params["record"] = recordFile;
    }

    HttpGo(context, json: false).post("/HiNote/UpdateHomeworkAnswer", params, (data) {
      widget.onSendDone();
      PageUtil().back(context);
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    return MyPage(
        "繳交作業",
        SingleChildScrollView(
            padding: EdgeInsets.only(top: 24),
            child: Column(children: [
              Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                LocalImage("tra.png", width: 40),
                Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.fromLTRB(16, 0, 16, 0),
                    height: 40,
                    color: Color(0xffffeade),
                    child:
                        Text("${widget.teacher} (${widget.teacherId})　${widget.date}", style: TextStyle(fontSize: 12, color: MyColor.C5)))
              ]),
              Container(
                padding: EdgeInsets.all(20),
                width: double.infinity,
                decoration: BoxDecoration(color: Color(0xffffeade), borderRadius: BorderRadius.only(topLeft: Radius.circular(20))),
                child: Text("Question：${widget.question}", style: TextStyle(fontSize: 12, color: MyColor.Orange)),
              ),
              Container(
                  margin: EdgeInsets.only(top: 8),
                  decoration: BoxDecoration(color: Color(0xffe2f2f2), borderRadius: BorderRadius.vertical(bottom: Radius.circular(20))),
                  padding: EdgeInsets.all(24),
                  child: Column(children: [
                    Container(
                        height: 140,
                        width: double.infinity,
                        color: MyColor.White,
                        padding: EdgeInsets.all(8),
                        child: NormalInput(
                            hintText: "請輸入回答...",
                            controller: answerController,
                            maxLines: 0,
                            hintColor: MyColor.Green,
                            fontColor: MyColor.Green)),
                    Container(height: 8),
                    DashBox(
                        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                      Text("檔案上傳", style: TextStyle(fontSize: 14, color: MyColor.Green)),
                      Container(height: 16),
                      ListView.builder(
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          itemCount: files.length,
                          itemBuilder: (c, i) {
                            return GestureDetector(
                                child: Container(
                                    padding: EdgeInsets.only(bottom: 6),
                                    child: Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
                                      LocalImage("file_g.png", width: 24, padding: EdgeInsets.fromLTRB(8, 0, 8, 0)),
                                      Expanded(child: Text("${files[i].path}", style: TextStyle(fontSize: 12, color: MyColor.Green))),
                                      LocalImage("del.png", width: 10, padding: EdgeInsets.all(8), onTap: () {
                                        delFile(i);
                                      })
                                    ])));
                          }),
                      Container(height: 8),
                      Container(
                          alignment: Alignment.centerRight,
                          child: BorderButton(
                              onTap: chooseFile,
                              child: Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
                                LocalImage("cloud-upload-g.png", width: 20),
                                Text("Upload files", style: TextStyle(fontSize: 15, color: MyColor.Green))
                              ])))
                    ])),
                    Container(height: 8),
                    DashBox(
                        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                      Text("錄音上傳", style: TextStyle(fontSize: 14, color: MyColor.Green)),
                      Container(height: 16),
                      Visibility(
                          visible: audioPath.isNotEmpty,
                          child: Row(children: [
                            Expanded(child: AudioPlayBarLocal(audioPath)),
                            LocalImage("del.png", width: 10, padding: EdgeInsets.all(8), onTap: () {
                              audioPath = "";
                              setState(() {});
                            })
                          ])),
                      Visibility(
                          visible: audioPath.isEmpty,
                          child: Container(
                              alignment: Alignment.centerRight,
                              child: RadioRecord(onRecordDone: (path) {
                                audioPath = path;
                                setState(() {});
                              })))
                    ])),
                    Container(height: 24),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Button("取 消", bgColor: MyColor.Green, isBorderBg: true, width: 64, height: 32, radius: 4, fontSize: 12, onTap: () {
                          PageUtil().back(context);
                        }),
                        Button("送 出", bgColor: MyColor.Green, width: 64, height: 32, radius: 4, fontSize: 12, onTap: sendClick)
                      ],
                    )
                  ])),
            ])));
  }
}

class DashBox extends StatelessWidget {
  Widget child;

  DashBox({required this.child});

  @override
  Widget build(BuildContext context) {
    return DottedBorder(
        color: MyColor.Green,
        child: Container(
          width: double.infinity,
          color: MyColor.White,
          padding: EdgeInsets.all(8),
          child: child,
        ));
  }
}

class BorderButton extends StatelessWidget {
  Widget child;
  Function()? onTap;

  BorderButton({required this.child, this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
          height: 28,
          width: 140,
          child: child,
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(16)),
              border: Border.all(width: 1, color: MyColor.Green))),
    );
  }
}

///錄音
class RadioRecord extends StatefulWidget {
  Function(String path) onRecordDone;

  RadioRecord({required this.onRecordDone});

  @override
  State<StatefulWidget> createState() {
    return _RadioRecord();
  }
}

class _RadioRecord extends State<RadioRecord> {
  final audioRecorder = Record();
  bool isRecording = false;
  bool isPaused = false;
  int recordDuration = 0;
  Timer? timer;

  @override
  void dispose() {
    timer?.cancel();
    audioRecorder.dispose();
    super.dispose();
  }

  Future<void> _start() async {
    try {
      if (await audioRecorder.hasPermission()) {
        await audioRecorder.start();
        bool isRecording = await audioRecorder.isRecording();
        setState(() {
          this.isRecording = isRecording;
          recordDuration = 0;
        });
        _startTimer();
      }
    } catch (e) {
      print(e);
    }
  }

  s2time(int s) {
    int mm = s ~/ 60;
    int ss = s % 60;
    String MM = TwoDigits(mm);
    String SS = TwoDigits(ss);
    return "$MM:$SS";
  }

  Future<void> _stop() async {
    timer?.cancel();
    final path = await audioRecorder.stop();
    print("recordPath:$path");
    widget.onRecordDone(path ?? "");
    setState(() => isRecording = false);
  }

  void _startTimer() {
    timer?.cancel();
    timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      setState(() => recordDuration++);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      BorderButton(
          child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        isRecording
            ? Container()
            : Container(height: 20, width: 20, decoration: Global.getBg(MyColor.Green, 10), margin: EdgeInsets.only(left: 6)),
        isRecording
            ? Container(height: 20, width: 20, decoration: Global.getBg(MyColor.Red, 10), margin: EdgeInsets.only(right: 6))
            : Container(),
      ])),
      Container(
          width: 140,
          height: 32,
          padding: EdgeInsets.fromLTRB(4, 0, 4, 0),
          child: isRecording
              ? Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                  TextBtn("Stop", height: 32, style: TextStyle(fontSize: 14, color: MyColor.C7D), onTap: _stop),
                  Text(s2time(recordDuration), style: TextStyle(fontSize: 14, color: MyColor.Red))
                ])
              : TextBtn("Record",
                  alignment: Alignment.centerRight, height: 32, style: TextStyle(fontSize: 14, color: MyColor.C7D), onTap: _start))
    ]);
  }
}
